package com.nineclock.attendance.job;

import com.nineclock.attendance.mapper.AttendGroupMapper;
import com.nineclock.attendance.pojo.AttendGroup;
import com.nineclock.attendance.service.AttendPunchService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SendAttendMailTask {

    @Autowired
    private AttendGroupMapper attendGroupMapper;

    @Autowired
    private AttendPunchService attendPunchService;

    @Autowired
    private SysUserFeign sysUserFeign;

    /**
     * 统计所有企业的本月的考勤报表数据信息
     */
    @XxlJob("countAttendanceAndSendMail")
    public void countAttendanceAndSendMail() throws MessagingException {

        //获取所有的企业ID
        List<Long> companyIds = queryCompanyIds();

        for (Long companyId : companyIds) {

            //遍历企业 , 根据企业ID统计该企业本月的考勤打卡数据 , 生成Excel -------> filename
            String filename = attendPunchService.generateExcelReportByCompanyId(companyId);

            //获取企业的主管理员
            SysCompanyUserDTO admin = sysUserFeign.queryAdminByCompanyId(companyId).getData();
            String email = admin.getEmail();

            //发送邮件
            sendMailAttachment(email, filename);
        }
    }




    /**
     * 获取所有的配置了考勤组的企业ID
     * @return
     */
    private List<Long> queryCompanyIds() {
        List<AttendGroup> attendGroups = attendGroupMapper.selectList(null);

        Set<Long> companyIds = attendGroups.stream().map(attendGroup -> {
            return attendGroup.getCompanyId();
        }).collect(Collectors.toSet());

        return new ArrayList<Long>(companyIds);
    }




    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendMailAttachment(String toMail , String filename) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setTo(toMail);
        mimeMessageHelper.setSubject("考勤报表数据");
        mimeMessageHelper.setText("您当前企业的员工考勤报表已生成, 请及时查收附件 , 谢谢!");

        mimeMessageHelper.addAttachment("考勤报表.xls", new File(filename));

        javaMailSender.send(mimeMessage);
    }

}
